<template>
  <div class="message-container" ref="messageContainer" >
    <MessageArea @submit="hanleSubmit" v-if="data" isloading="isloading" title="留言板" :list="data.rows" :subTitle="data.total"></MessageArea>
  </div>
</template>

<script>
import {getMessage} from "../../api/message.js"
import {PostMessage} from "../../api/message.js"
import fetchData from "../../mixins/fetchData"
import MessageArea from "../../components/MessageArea/index.vue"
import setmainScroll from "../../mixins/setmainScroll"
export default {
  data(){
return{
  page:1,
  limit:10
}
  },
  mixins:[fetchData({total:0,rows:[]}),setmainScroll('messageContainer')],
components:{
    MessageArea,
    MessageArea
},
computed:{
hasMore(){
    return this.data.rows.length<this.data.total;
  },

},
created(){
  this.$Bus.$on('mainScroll',this.hanleMove)
},
destroyed(){
  this.$Bus.$emit('mainScroll')
  this.$Bus.$off('mainScroll',this.hanleMove)

},
methods:{
  async fetchData(){
return await getMessage(this.page, this.limit);
  },
     hanleMove(dom){
       const range=100;
       if( this.isloading || !dom ){
         return;
       }
     const spacing=Math.abs(dom.scrollHeight-(dom.scrollTop+dom.clientHeight)) ;
     if(range>=spacing){
      this.fetchMove();
  }
    //  console.log(1)
  },
 async fetchMove(){
      if(!this.hasMore){
        return;
      }
      this.isloading=true;  
      this.page++;
      const resp= await this.fetchData();
     
       if(this.data.total<resp.total){
         return
       }
      this.data.total = resp.total;
      this.data.rows= this.data.rows.concat(resp.rows);
      this.isloading=false;
       console.log(1)
      },

async  hanleSubmit(e,callback){
  const resp =await PostMessage(e.nickname,e.content)
callback('感谢您的指点');
this.data.rows.unshift(resp);
this.data.total++;
  }
}
}
</script>

<style lang="less" scoped>
.message-container{
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 30px;
  overflow-y:scroll;

}
</style>